<script lang="ts" setup name="PatientPage">
import type { Patient, PatientList } from '@/types/user'
import { ref, onMounted, computed, watch } from 'vue'
import { getPatientList, addPatient, updatePatient, deletePatient } from '@/api/user'
import { nameRules, idCardRules } from '@/utils/rules'
import type { FormInstance } from 'vant'
import { showConfirmDialog } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { useConsultStore } from '@/stores'
const store = useConsultStore()
const route = useRoute()
const router = useRouter()
// 是否是选择患者（地址栏中的所有参数的类型是字符串）
const isSelect = computed(() => route.query.isSelect === '1')
const patientId = ref('')
const patientList = ref<PatientList>([])
const getData = async () => {
  const res = await getPatientList()
  patientList.value = res.data
  // 给选中的患者id，赋默认值
  if (res.data.length > 0) {
    let selectPatient = res.data.find(item => item.defaultFlag === 1)
    if (selectPatient) {
      patientId.value = selectPatient.id!
    } else {
      patientId.value = res.data[0].id!
    }
  }
}
onMounted(() => {
  getData()
})
// 显示弹出层
const show = ref(false)
const addOrEdit = (patientObj?: Patient) => {
  if (patientObj) {
    // 修改（结构，相当于对patientObj对象做了一次深拷贝）
    const { id, name, idCard, gender, defaultFlag } = patientObj

    patient.value = {
      id,
      name,
      idCard,
      gender,
      defaultFlag
    }
  }
  show.value = true
}
// 保存（新增、修改）
const formRef = ref<FormInstance>()
const save = async () => {
  // 校验必填的字段
  try {
    await formRef.value?.validate()

    // 调用接口
    patient.value.id ? await updatePatient(patient.value) : await addPatient(patient.value)

    // 关闭弹出层
    show.value = false

    // 重新加载
    getData()
  } catch (error) {}
}
const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]
// 定义模型数据（供新增&修改患者信息用）
const patient = ref({
  gender: 1, // 默认值 男
  defaultFlag: 0 // 默认值0
} as Patient)

// 计算属性（完整写法）
const isDefault = computed({
  get() {
    return patient.value.defaultFlag === 1 ? true : false
  },
  set(val: boolean) {
    patient.value.defaultFlag = val ? 1 : 0
  }
})

const clear = () => {
  // 数据驱动视图
  patient.value = {
    id: '',
    name: '',
    idCard: '',
    gender: 1,
    defaultFlag: 0
  }
}

watch(show, val => {
  if (!val) {
    clear()
  }
})

// 删除
const del = async (id: string) => {
  try {
    await showConfirmDialog({
      title: '提示',
      message: '确定删除吗'
    })

    // 调用接口
    await deletePatient(id)

    // 关闭popup
    show.value = false

    // 重新加载
    getData()
  } catch (error) {
    console.log('---error---', error)
  }
}
const next = () => {
  // 保存患者信息到仓库
  store.setPatientId(patientId.value)

  // 跳转到下单页面
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <cp-nav-bar :title="isSelect ? '选择患者' : '家庭档案'"></cp-nav-bar>
    <!-- 头部提示 -->
    <div class="patient-change" v-if="isSelect">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <div class="patient-list">
      <div
        class="patient-item"
        :class="{ selected: item.id === patientId }"
        v-for="item in patientList"
        :key="item.id"
        @click="patientId = item.id!"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <!-- <span class="id">{{
            item.idCard.substring(0, 6) + '******' + item.idCard.substring(14)
          }}</span> -->
          <span class="id">{{ item.idCard.replace(/(.{6}).*(.{4})/, '$1********$2') }}</span>
          <span>{{ item.genderValue }}</span>
          <span>{{ item.age }}岁</span>
        </div>
        <div class="icon"><cp-icon name="user-edit" @click="addOrEdit(item)" /></div>
        <div class="tag" v-if="item.defaultFlag === 1">默认</div>
      </div>
      <div class="patient-add" v-if="patientList.length < 6" @click="addOrEdit()">
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加 6 人</div>
    </div>
    <!-- 底部按钮 -->
    <div class="patient-next" v-if="isSelect">
      <van-button type="primary" :disabled="!patientId" @click="next" round block
        >下一步</van-button
      >
    </div>
    <!-- 右侧弹出 -->
    <!-- <van-popup
      v-model:show="show"
      position="right"
      :style="{ width: '100%', height: '100%' }"
      @close="clear"
    > -->
    <van-popup v-model:show="show" position="right" :style="{ width: '100%', height: '100%' }">
      <cp-nav-bar
        :title="patient.id ? '修改患者' : '添加患者'"
        right-text="保存"
        @right-click="save"
        :back="() => (show = false)"
      />
      <van-form ref="formRef">
        <van-field
          placeholder="请输入真实姓名"
          label="真实姓名"
          :rules="nameRules"
          v-model="patient.name"
          name="name"
        />
        <van-field
          placeholder="请输入身份证号"
          label="身份证号"
          :rules="idCardRules"
          v-model="patient.idCard"
          name="idCard"
        />
        <van-field label="性别">
          <template #input>
            <cp-radio-button :options="options" v-model="patient.gender" />
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox v-model="isDefault" />
          </template>
        </van-field>
      </van-form>
      <van-action-bar v-if="patient.id">
        <van-action-bar-button @click="del(patient.id!)">删除</van-action-bar-button>
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 0px 0 80px;
}
.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
.pb4 {
  padding-bottom: 4px;
}

// 底部操作栏
.van-action-bar {
  padding: 0 10px;
  margin-bottom: 10px;
  .van-button {
    color: var(--cp-price);
    background-color: var(--cp-bg);
  }
}
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}
</style>
